// @ts-nocheck
import type {Settings as LayoutSettings} from '@ant-design/pro-layout';
import {SettingDrawer} from '@ant-design/pro-layout';
import {PageLoading} from '@ant-design/pro-layout';
import type {RunTimeLayoutConfig} from 'umi';
import {history} from 'umi';
import RightContent from '@/components/RightContent';
import Footer from '@/components/Footer';
import defaultSettings from '../config/defaultSettings';
import {getUser} from '@/services/user'
import {message} from 'antd'
import type {RequestConfig} from "@@/plugin-request/request";
import logos from '@/assets/1.png'

const loginPath = '/user/login';
const filterUrl = ['/api/business/contract', '/api/business/client', '/api/system/getExcelData']
const downloadUrl = ['/api/resource/downloadResource', '/api/business/download/example', '/api/network/downloadHost', '/api/business/client/example','/api/system/package/downloadPackage']
// const codeMessage = {
//   200: '服务器成功返回请求的数据。',
//   201: '新建或修改数据成功。',
//   202: '一个请求已经进入后台排队（异步任务）。',
//   204: '删除数据成功。',
//   400: '发出的请求有错误，服务器没有进行新建或修改数据的操作。',
//   401: '用户没有权限（令牌、用户名、密码错误）。',
//   403: '用户得到授权，但是访问是被禁止的。',
//   404: '发出的请求针对的是不存在的记录，服务器没有进行操作。',
//   406: '请求的格式不可得。',
//   410: '请求的资源被永久删除，且不会再得到的。',
//   422: '当创建一个对象时，发生一个验证错误。',
//   500: '服务器发生错误，请检查服务器。',
//   502: '网关错误。',
//   503: '服务不可用，服务器暂时过载或维护。',
//   504: '网关超时。',
//   900: 'token过期',
// };
const errorHandler = (error: { response: any }) => {
  const {response} = error;
  if (response && response.status) {

    if (response.status === 404) {
      message.error('用户名或密码错误！')
    } else if (response.status === 403) {
      message.error('缺少接口权限，请联系管理员！')
    } else if (response.status === 400) {
      message.error('网络异常')
    }

  }
  return response;
};

export const request: RequestConfig = {
  timeout: 100000,
  errorHandler,
  errorConfig: {},
  middlewares: [],
  requestInterceptors: [
    (url, options) => {
      if (downloadUrl.includes(url) && options.method === 'get') {
        return {
          url,
          options: {
            ...options,
            headers: {Authorization: `${sessionStorage.getItem('token') || ''} `},
            responseType: 'blob'
          },
        };
      }
      if (filterUrl.includes(url)) {
        return {
          url,
          options: {
            ...options,
            headers: {Authorization: `${sessionStorage.getItem('token') || ''} `},
          },
        };
      }

      return {
        url,
        options: {
          ...options,
          headers: {
            Authorization: sessionStorage.getItem('token') || '',
            'Content-Type': 'application/json',
            Accept: 'application/json',
          },
        },
      };


    },
  ],
  responseInterceptors: [
    async (response) => {
      if (response.status === 401) {
        // token过期的时候自动刷新获取新的token自动登录，当然这是根据自己页面的需求决定，大多都是token过期跳转登录页面，重新登陆
        message.error('登录超时，请重新登录！')
        history.replace('/user/login');
      }
      return response;
    },
  ],
};

/** 获取用户信息比较慢的时候会展示一个 loading */
export const initialStateConfig = {
  loading: <PageLoading/>,
};

/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState(): Promise<{
  settings?: Partial<LayoutSettings>;
  currentUser?: API.CurrentUser;
  loading?: boolean;
  fetchUserInfo?: () => Promise<API.CurrentUser | undefined>;
}> {
  const fetchUserInfo = async () => {
    try {
      // @ts-ignore
      const msg = await getUser();
      return msg.data;
    } catch (error) {
      history.push(loginPath);
    }
    return undefined;
  };
  // 如果不是登录页面，执行

  if (history.location.pathname !== loginPath) {
    const currentUser = await fetchUserInfo();
    console.log(currentUser)
    return {
      fetchUserInfo,
      currentUser,
      settings: defaultSettings,
    };
  }
  return {
    fetchUserInfo,
    settings: defaultSettings,
  };
}

const logo = sessionStorage.getItem('左上方logo') ? sessionStorage.getItem('左上方logo') : logos
const text = sessionStorage.getItem('左上方文字') ? sessionStorage.getItem('左上方文字') : '计费运维平台'
// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout: RunTimeLayoutConfig = ({initialState, setInitialState}) => {
  return {
    rightContentRender: () => <RightContent/>,
    disableContentMargin: false,
    logo,
    title: text,
    footerRender: () => <Footer/>,
    onPageChange: () => {
      const {location} = history;
      // 如果没有登录，重定向到 login
      if (!initialState?.currentUser && location.pathname !== loginPath) {
        history.push(loginPath);
      }
    },
    links: [],
    menuHeaderRender: undefined,
    // 自定义 403 页面
    // unAccessible: <div>unAccessible</div>,
    // 增加一个 loading 的状态
    childrenRender: (children, props) => {
      // if (initialState?.loading) return <PageLoading />;
      return (
        <>
          {children}
          {!props.location?.pathname?.includes('/login') && (
            <SettingDrawer
              disableUrlParams
              enableDarkTheme
              settings={initialState?.settings}
              onSettingChange={(settings) => {
                setInitialState((preInitialState) => ({
                  ...preInitialState,
                  settings,
                }));
              }}
            />
          )}
        </>
      );
    },
    ...initialState?.settings,
  };
};
